// ignore: implementation_imports, import_of_legacy_library_into_null_safe
import 'package:build/src/builder/build_step.dart';
import 'package:analyzer/dart/element/element.dart' as ele;
import 'route.dart';
import 'dart:async';

// ignore: import_of_legacy_library_into_null_safe
import 'package:source_gen/source_gen.dart';

// ignore: import_of_legacy_library_into_null_safe
import 'package:build/build.dart';
import 'dart:io';
import 'tpl/tpl.dart' as tpl;

class RouteGenerator extends GeneratorForAnnotation<GRoute> {
  final separator = Platform.pathSeparator;
  final Map constantMap = Map();
  final Map routesMap = Map();
  final Map importMap = Map();
  var defaultRoute = "";
  var debugRoute = "";
  var lastRoutesLen = 0;
  Timer? timer;

  String buildConstant(map, defaultRoute, debugRoute) {
    var sb = StringBuffer();
    map.forEach((key, value) {
      if (value == defaultRoute) {
        sb.writeln("  /// 入口页面");
      } else if (value == debugRoute) {
        sb.writeln("  /// debug页面");
      }
      sb.writeln("  static const String $value = '$key';");
    });
    return sb.toString();
  }

  String buildWidgetName(map) {
    var sb = StringBuffer();
    map.forEach((key, value) {
      sb.writeln("    RouteConstant.$value: '$value',");
    });
    return sb.toString();
  }

  String buildRoutes(map, defaultRoute) {
    var sb = StringBuffer();
    map.forEach((key, value) {
      if (key == defaultRoute) {
        sb.writeln("    RouteConstant.$key: (context) {");
        sb.writeln("      ScreenSizeFit.init(context);");
        sb.writeln("      return $key(title: '$value');");
        sb.writeln("    },");
      } else {
        sb.writeln(
            "    RouteConstant.$key: (context) => $key(title: '$value'),");
      }
    });
    return sb.toString();
  }

  String buildImport(map) {
    var sb = StringBuffer();
    map.forEach((key, value) {
      sb.writeln("import '$key';");
    });
    return sb.toString();
  }

  @override
  generateForAnnotatedElement(
      ele.Element element, ConstantReader annotation, BuildStep buildStep) {
    var enable = false;
    try {
      enable = annotation.read('enable').boolValue;
    } catch (e) {}
    if (!enable) return null;
    var url, title;
    int debounceTime = 1000;
    try {
      url = annotation.read('url').stringValue;
    } catch (e) {}
    try {
      title = annotation.read('title').stringValue;
    } catch (e) {}
    try {
      debounceTime = annotation.read('debounceTime').intValue;
    } catch (e) {}
    if (url == '/') {
      //入口
      defaultRoute = element.name!;
    } else if (url == '/debug') {
      debugRoute = element.name!;
    }
    constantMap[url] = element.name;
    routesMap[element.name] = title;
    if (buildStep.inputId.path.contains('lib/')) {
      importMap[
              "package:${buildStep.inputId.package}/${buildStep.inputId.path.replaceFirst('lib/', '')}"] =
          null;
    }
    //优化多个执行，会导致先收集的后执行，导致生成数据不准确
    if (routesMap.length > lastRoutesLen) {
      lastRoutesLen = routesMap.length;
      if (timer != null && timer!.isActive) {
        timer!.cancel();
      }
      timer = Timer(Duration(milliseconds: debounceTime), () {
        File(
            '${Directory.current.path}${separator}lib${separator}route${separator}main.route.dart')
          ..createSync(recursive: true)
          ..writeAsStringSync(tpl.clazzTpl(
              buildConstant:
                  buildConstant(constantMap, defaultRoute, debugRoute),
              buildWidgetName: buildWidgetName(constantMap),
              buildRoutes: buildRoutes(routesMap, defaultRoute),
              buildImport: buildImport(importMap),
              defaultRoute: defaultRoute,
              package: buildStep.inputId.package));
        timer!.cancel();
      });
    }
    return null;
  }
}

Builder routeBuilder(BuilderOptions options) =>
    LibraryBuilder(RouteGenerator(), generatedExtension: ".route.dart");
